<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Outlet extends MX_Controller {
  function __construct() {
    $this->load->library('template');
    $this->load->library('form_eksternal');
    $this->load->library('global_models');
    $this->load->library('mobile_detect');
    $this->load->library('nbscache');
    $this->load->library('PHPExcel');
    $this->load->library('encrypt');
    $this->load->helper('path');
    $this->load->helper('url');
    $this->load->model('outlet/moutlet');
    $this->load->library('parser');
    $this->load->library('session');
    $this->load->library('form_validation');
    $this->load->library('pagination');
    $this->menu = $this->cek();
    
    
  }
	public function add_row(){
//    (, , "user_hidden", site_url("outlet/add_row"), "mul_users", "add_users", "nomor", "user", , "", "")
    $no = rand(100, 100000);
    $isi = $this->form_eksternal->form_autocomplate("user_view[]", "users[]", "users_".$no, "user_hidden_".$no, site_url("outlet/sementara"), "", "");
    print <<<EOD
    <tr id="tr_{$no}"><td>{$isi}</td>
   <td><a href='#' class='remove-element' onclick="del_row_tambahan('tr_{$no}')" title='Remove' >Remove</a></td></tr>
EOD;
    die;
  }
	public function sementara(){
    
// no term passed - just exit early with no response
    if (empty($_GET['term'])) exit ;
    $q = strtolower($_GET["term"]);
// remove slashes if they were magically added
    if (get_magic_quotes_gpc()) $q = stripslashes($q);

    $items = $this->moutlet->get_user_auto($q);
    $result = array();
    foreach ($items as $key=>$value) {
      if (strpos(strtolower($key), $q) !== false) {
        array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
      }
      if (count($result) > 11)
        break;
    }

// json_encode is available in PHP 5.2 and above, or you can install a PECL module in earlier versions
    echo json_encode($result);
    die;
  }
	public function detail($id){
    $newdata = array(
      'outlet'  => $id
    );
    $this->session->set_userdata($newdata);
    redirect("outlet/aktifitas/daftar");
  }
	public function milik($id = 0){
    if($id <= 0){
      if($this->session->userdata("id") > 0)
        $id = $this->session->userdata("id");
    }
    $list = $this->moutlet->get_milik($id);
    $this->template->title('Sistem', "Outlet");
    
    $view = "milik";
    if($this->mobile_detect->isMobile()){
      $view = "mobile/m-milik";
    }
    
    $this->template->build($view, 
      array('message' => "",
            'url'     => base_url()."themes/srabon/",
            'data'    => $list,
            'menu_drop'   => $this->menu,
            'menu'        => "settings",
            'title_table'    => "Outlet Data Table",
            'foot'    => ""
          ));
    $this->template
      ->set_layout('default')
      ->build($view);
  }
  
  function pica_all(){
    
    if($this->input->post("report", TRUE)){
      $this->moutlet->pica_report_xls();
    }
    if($this->input->post("rekap", TRUE)){
      $this->moutlet->pica_rekap_xls();
    }
       
  //echo $this->session->userdata("id_privilege"); exit;
        $parent = array(
        1 => "SDM",
        2 => "Service",
        3 => "Administrasi",
        4 => "Promo",
        5 => "Tools",
        6 => "IT - Software & Hardware",
        7 => "Parts",
        9 => "Lainnya"
    );
        
        $status = array(
            "all" => "All",
            0 => "Draft",
            1 => "Progress",
            2 => "Finish",
        );
        
        $berdasar = array(
            "tanggal_buat"      => "Report Date",
            "due_date"          => "Due Date",
            "tanggal_selesai"   => "Finish Date",
        );
       
       //  $dropdown = array();
        $dropdown = array_reverse($parent, true);
   // $this->template->title('Sistem', "Outlet");
       $pr = $this->nbscache->get_explode("pica_permission", $this->session->userdata("id_privilege"));
       $pica_ca = unserialize($pr[1]);

       if($this->session->userdata("id_privilege") > 0){
       $parent = array_intersect($parent, $pica_ca);
      
       $dropdown = array_intersect($dropdown, $pica_ca);
       }else{
           $dropdown = $dropdown;
       }
         
      if(is_array($dropdown)){
      foreach ($dropdown as $key => $value) {
        $dropdown[$key] = $value;
      }
    }
    $dropdown[0] = "-- Pilih --";
   $dropdown = array_reverse($dropdown, true);
   
//   $status[0] = "-- Pilih --";
//  $status =   array_reverse($status, true);
    // $dropdown =  array_merge($dropdown, $parent);
   
    if($this->input->post() AND !$this->input->post("export", TRUE)){
      
//   if($this->input->post("export", TRUE)){
//       $session_xls = array(
//            "pica_search_export1"        => $this->input->post("export"),
//           "pica_search_outlet1"        => $this->input->post("outlet"),
//            "pica_search_id_kategori1"         => $this->input->post("id_kategori"),
//            "pica_search_id_fix1"       => $this->input->post("id_fix"),
//            "pica_search_bc_name1"   => $this->input->post("bc_name"),
//            "pica_search_start_date1"  => $this->input->post("start_date"),
//            "pica_search_end_date1"     => $this->input->post("end_date"),
//        );
//       $this->session->set_userdata($session_xls);
//       
//     $session_cari = array(
//            "pica_search_outlet"        => "",
//            "pica_search_id_kategori"         => "",
//            "pica_search_id_fix"   => "",
//            "pica_search_bc_name"  => "",
//            "pica_search_start_date"     => "",
//            "pica_search_end_date"    => "",
//        );
//        $this->session->unset_userdata($session_cari);
//      }
      if($this->input->post('cari') == 's'){
        $session_cari = array(
            "pica_search_outlet"              => $this->input->post("id_outlet"),
            "pica_search_id_kategori"         => $this->input->post("id_kategori"),
            "pica_search_id_fix"              => $this->input->post("id_fix"),
            "pica_search_start_date"          => $this->input->post("start_date"),
            "pica_search_end_date"            => $this->input->post("end_date"),
            "pica_search_date_berdasar"       => $this->input->post("date_berdasar"),
            "pica_sort"                       => $this->input->post("sort"),
        );
        $this->session->set_userdata($session_cari);
        redirect("outlet/pica-all");
      }
      else{
        $session_cari = array(
            "pica_search_outlet"        => "",
            "pica_search_id_kategori"         => "",
            "pica_search_id_fix"   => "1",
            "pica_search_bc_name"  => "",
            "pica_search_start_date"     => "",
            "pica_search_end_date"    => "",
            "pica_search_date_berdasar"       => "tanggal_buat",
            "pica_sort"                       => "A.due_date ASC",
        );
        $this->session->set_userdata($session_cari);
        redirect("outlet/pica-all");
      }
     
      
    }
   
 
//    foreach ($parent as $ky => $prt){
    
    if(!$this->session->userdata("pica_search_id_fix"))
      $this->session->set_userdata(array("pica_search_id_fix" => 1));
        
      if($this->session->userdata("pica_search_outlet")){
      $where .= " AND A.id_outlet = {$this->session->userdata("pica_search_outlet")} ";
      }

      if($this->session->userdata("pica_search_id_kategori")){
        $where .= " AND A.kategori = {$this->session->userdata("pica_search_id_kategori")} ";
      }

      if($this->session->userdata("pica_search_id_fix") != "" AND $this->session->userdata("pica_search_id_fix") != "all"){
        $where .= " AND A.fix = {$this->session->userdata("pica_search_id_fix")} ";
      }

      if($this->session->userdata("pica_search_start_date")){
        $where .= " AND (A.{$this->session->userdata("pica_search_date_berdasar")} BETWEEN '{$this->session->userdata("pica_search_start_date")}' AND '{$this->session->userdata("pica_search_end_date")}') ";
      }
    
      $data = $this->global_models->get_query("
      SELECT count(id_history) AS jumlah FROM d_history AS A WHERE 1=1 {$where}
         ORDER BY  `A`.`create_date` ASC
      "); 
      
//    $data_export[$ky] = $this->global_models->get_query("
//        SELECT A . * , B.name AS laporan, C.name AS name_outlet FROM d_history AS A
//        LEFT JOIN m_actifity_report AS B ON A.id_actifity_report = B.id_actifity_report
//        LEFT JOIN m_outlet AS C ON B.id_outlet = C.id_outlet
//		$data_join
//        LEFT JOIN d_pic_users as D on A.id_pic_users = D.id_pic_users
//        LEFT JOIN m_users as E on D.id_users = E.id_users
//        LEFT JOIN d_user_privilege F ON F.id_users = E.id_users
//       where  $queryData $queryWhere $query2 $query $query1
//       ORDER BY  `A`.`create_date` ASC 
//      "); 
//     
//      }
      if($this->input->post("export", TRUE)){
        if($this->session->userdata("pica_sort")){
      $sorting = $this->session->userdata("pica_sort");
    }
    else{
      $sorting = "A.due_date ASC";
    }
    
    if($this->session->userdata("pica_search_outlet")){
      $where_eks .= " AND A.id_outlet = {$this->session->userdata("pica_search_outlet")} ";
    }
    
    if($this->session->userdata("pica_search_id_kategori")){
      $where_eks .= " AND A.kategori = {$this->session->userdata("pica_search_id_kategori")} ";
    }
    
    if($this->session->userdata("pica_search_id_fix") != "" AND $this->session->userdata("pica_search_id_fix") != "all"){
      $where_eks .= " AND A.fix = {$this->session->userdata("pica_search_id_fix")} ";
    }
    
    if($this->session->userdata("pica_search_start_date")){
      $where_eks .= " AND (A.{$this->session->userdata("pica_search_date_berdasar")} BETWEEN '{$this->session->userdata("pica_search_start_date")}' AND '{$this->session->userdata("pica_search_end_date")}') ";
    }
    
        $data_export = $this->global_models->get_query("
         SELECT A.*, B.name as outlet, C.name AS pic, D.name AS kategori_pica
         FROM d_history AS A
         LEFT JOIN m_outlet AS B ON A.id_outlet = B.id_outlet
         LEFT JOIN m_pic_pica AS C ON A.id_pic_pica = C.id_pic_pica
         LEFT JOIN m_kategori_pica AS D ON A.id_kategori_pica = D.id_kategori_pica
         WHERE 1=1 {$where_eks}
         ");
    
//        $this->debug($data_export, true);
     // echo $this->session->userdata('pica_search_export1'); echo $this->session->userdata('pica_search_id_kategori1'); die;
        $this->moutlet->pica_all_xls($parent,$data_export);
        
      }
    if(!$this->input->post(NULL, TRUE)){
      $this->template->build('pica-all', 
        array(
              'message'     => "",
              'url'     => base_url()."themes/srabon/",
              'menu_drop'   => $this->menu,
              'menu'        => "outlet",
              'detail'        => $detail,
              'data_total'        => $data,
               'pagerow'  => $pages,
              'parent'        => $parent,
            'fix'   => $status,
            'dropdown'        => $dropdown,
              'title_table'    => "PICA All Outlet",
            'search_table'    => "Search PICA",
            'berdasar'    => $berdasar,
              'foot'    => ""
            ));
      $this->template
        ->set_layout('default')
        ->build('pica-all');
    } 
  }
  
  public function ajax_pica_all($total = 0, $start = 0){
    
//    $session_cari = array(
//        "pica_search_outlet"              => $this->input->post("outlet"),
//        "pica_search_id_kategori"         => $this->input->post("id_kategori"),
//        "pica_search_id_fix"              => $this->input->post("id_fix"),
//        "pica_search_start_date"          => $this->input->post("start_date"),
//        "pica_search_end_date"            => $this->input->post("end_date"),
//        "pica_sort"                       => $this->input->post("sort"),
//    );
    if($this->session->userdata("pica_sort")){
      $sorting = $this->session->userdata("pica_sort");
    }
    else{
      $sorting = "A.due_date ASC";
    }
    
    if($this->session->userdata("pica_search_outlet")){
      $where .= " AND A.id_outlet = {$this->session->userdata("pica_search_outlet")} ";
    }
    
    if($this->session->userdata("pica_search_id_kategori")){
      $where .= " AND A.kategori = {$this->session->userdata("pica_search_id_kategori")} ";
    }
    
    if($this->session->userdata("pica_search_id_fix") != "" AND $this->session->userdata("pica_search_id_fix") != "all"){
      $where .= " AND A.fix = {$this->session->userdata("pica_search_id_fix")} ";
    }
    
    if($this->session->userdata("pica_search_start_date")){
      $where .= " AND (A.{$this->session->userdata("pica_search_date_berdasar")} BETWEEN '{$this->session->userdata("pica_search_start_date")}' AND '{$this->session->userdata("pica_search_end_date")}') ";
    }
    
     $data = $this->global_models->get_query("
      SELECT A.*, B.name as outlet, C.name AS pic, D.name AS kategori_pica
      FROM d_history AS A
      LEFT JOIN m_outlet AS B ON A.id_outlet = B.id_outlet
      LEFT JOIN m_pic_pica AS C ON A.id_pic_pica = C.id_pic_pica
      LEFT JOIN m_kategori_pica AS D ON A.id_kategori_pica = D.id_kategori_pica
      WHERE 1=1 {$where}
      ORDER BY {$sorting} LIMIT {$start},10
      ");
    
    $kategori = array(
        1 => "SDM",
        2 => "Service",
        3 => "Administrasi",
        4 => "Promo",
        5 => "Tools",
        6 => "IT - Software & Hardware",
        7 => "Parts",
        9 => "Lainnya"
    );
    
    $sumber = array(
        1 => "Email",
        2 => "Telphone",
        3 => "Pesan Singkat",
    );
    $status = array(
        0 => "<span class='label'>Draft</span>",
        1 => "<span class='label label-info'>Progress</span>",
        2 => "<span class='label label-success'>Finish</span>",
    );
    $panggilan = array(
        1 => "Bapak",
        2 => "Ibu",
    );
    
    $post_fix = site_url("outlet/post-fix");
    
     
    foreach ($data as $key => $value) {
      
      $awal_time = strtotime($value->tanggal_buat);
      $selesai_time = strtotime($value->tanggal_selesai);
      $over_time = strtotime($value->due_date);
      if($value->tanggal_selesai)
        $sekarang = gregoriantojd(date("m", $selesai_time), date("d", $selesai_time), date("Y", $selesai_time));
      else
        $sekarang = gregoriantojd(date("m"), date("d"), date("Y"));

      $awal_laporan = gregoriantojd(date("m", $awal_time), date("d", $awal_time), date("Y", $awal_time));
      $lama_laporan = $sekarang - $awal_laporan;

      if($value->tanggal_selesai){
        $selesai_laporan = gregoriantojd(date("m", $selesai_time), date("d", $selesai_time), date("Y", $selesai_time));
        $lama_pengerjaan = $selesai_laporan - $awal_laporan;
        $sekarang_over = $selesai_laporan;
      }
      else{
        $lama_pengerjaan = "-";
        $sekarang_over = $sekarang;
      }

      $over_laporan = gregoriantojd(date("m", $over_time), date("d", $over_time), date("Y", $over_time));
      $lama_kelewatan =  $sekarang_over - $over_laporan;
      if($lama_kelewatan < 0){
        $cetak_over = "";
      }
      else{
        $cetak_over = "<br /> Over Due : {$lama_kelewatan} hari";
      }
      
      $benar = FALSE;
      $disable = '';
      if($value->fix == 2){
        $benar = TRUE;
        $disable = 'disabled';
      }
      
      $history_data = $this->global_models->get("d_history_log", array("id_history" => $value->id_history));
      $history = "";
      foreach($history_data as $hd){
        $history .= "
          <p><h5>{$hd->tanggal}</h5>
            ".  nl2br($hd->note)."
          </p>
          ";
      }
      
      print "
      <tr class='ajax-pica'>
        <td>
          <a href='#myModal_{$value->id_history}' data-toggle='modal'>{$value->outlet}</a>
          <div class='modal hide fade' id='myModal_{$value->id_history}'>
            <div class='modal-header'>
              <button type='button' class='close' data-dismiss='modal'>×</button>
              <h3>Log</h3>
            </div>
            <div class='modal-body'>
              {$history}
            </div>
            <div class='modal-footer'>
              <a href='#' class='btn' data-dismiss='modal'>Close</a>
            </div>
          </div>
        </td>
        <td>
          Topik : {$kategori[$value->kategori]}
          <br /> Kategori : {$value->kategori_pica}
          <br /> Sumber : {$sumber[$value->sumber_info_view]}
          <br /> Status : <span id='status_view_{$value->id_history}'>{$status[$value->fix]}</span>
          <br /> Pelapor : <b>{$panggilan[$value->panggilan]} {$value->nama_pelapor}</b>
          <br /> Email : <b>{$value->email_pelapor}</b>
          <br /> Telphone : <b>{$value->telp_pelapor}</b>
        </td>
        <td>{$value->problem}</td>
        <td>{$value->corrective}</td>
        <td>
          <span id='info_waktu_{$value->id_history}'>
            Report Date : {$value->tanggal_buat}
          <br /> Due Date : {$value->due_date}
          <br /> Finish Date : {$value->tanggal_selesai}
          <br /> Lama Laporan : {$lama_laporan} hari
          {$cetak_over}
          <br /> PIC : {$value->pic}</span>
        </td>
        <td>
          ".$this->form_eksternal->form_checkbox("fix[{$value->id_history}]", "{$value->id_history}", $benar, "id='fix_{$value->id_history}' {$disable}")."
          <script>
            $(document).ready(function(){
              $('#fix_{$value->id_history}').click(function(){
                if($(this).attr('checked') == 'checked'){
                  $.post('{$post_fix}',{id: {$value->id_history}, fix: '1'},function(data){
                    $('#info_waktu_{$value->id_history}').html(data);
                    $('#status_view_{$value->id_history}').html('<span id=finish_{$value->id_history} class=label>Finish</span>');
                    $('#finish_{$value->id_history}').addClass('label-success');
                  });
                  eval($(this).prop('disabled', true));
                }
              });
            });
          </script>
          <br /> <a href='".site_url("customer-service/add-pica/".$value->id_history)."'>Detail</a>
        </td>
      </tr>
      ";
      
    }
    
    $this->load->library('pagination');

    $config['base_url'] = '';
    $config['total_rows'] = $total;
    $config['per_page'] = 10; 
    $config['uri_segment'] = 4; 
    $config['cur_tag_open'] = "<li class='active'><a href='javascript:void(0)'>"; 
    $config['cur_tag_close'] = "</a></li>"; 
    $config['first_tag_open'] = "<li>"; 
    $config['first_tag_close'] = "</li>"; 
    $config['last_tag_open'] = "<li>"; 
    $config['last_tag_close'] = "</li>"; 
    $config['next_tag_open'] = "<li>"; 
    $config['next_tag_close'] = "</li>"; 
    $config['prev_tag_open'] = "<li>"; 
    $config['prev_tag_close'] = "</li>"; 
    $config['num_tag_open'] = "<li>"; 
    $config['num_tag_close'] = "</li>";
    $config['function_js'] = "load_pica";

    $this->pagination->initialize($config); 
    print "
    <tr class='ajax-pica'>
      <td colspan='6'>
        <div class='pagination'>
          <ul>
          ".$this->pagination->create_links_ajax()."
          </ul>
        </div>
      </td>
    </tr>";
    die;
  }
   
  function autooutlet(){
    if (empty($_GET['term'])) exit ;
    $q = strtolower($_GET["term"]);
    if (get_magic_quotes_gpc()) $q = stripslashes($q);
    $items = $this->moutlet->get_auto_outlet($q);
    $result = array();
    foreach ($items as $key=>$value) {
      if (strpos(strtolower($key), $q) !== false) {
        array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
      }
      if (count($result) > 11)
        break;
    }
    echo json_encode($result);
    die;
  }
  
  function autobc(){
    if (empty($_GET['term'])) exit ;
    $q = strtolower($_GET["term"]);
    if (get_magic_quotes_gpc()) $q = stripslashes($q);
    $items = $this->moutlet->get_auto_bc($q);
    $result = array();
    foreach ($items as $key=>$value) {
      if (strpos(strtolower($key), $q) !== false) {
        array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
      }
      if (count($result) > 11)
        break;
    }
    echo json_encode($result);
    die;
  }
  
  function setting_privilege_pica(){
      
     $dropdown = $this->global_models->get_dropdown("m_privilege", "id_privilege", "name", TRUE, array("parent > " => 0));
       $this->template->build('privilege-pica', 
        array(
              'message'     => "",
              'url'     => base_url()."themes/srabon/",
              'menu_drop'   => $this->menu,
              'menu'        => "outlet",
              'detail'        => $data_detail,
            'dropdown'  => array($dropdown),
              'data'        => $data,
               'pagerow'  => $pages,
              'parent'        => $parent,
              'title_table'    => "Privilege Pica",
              'foot'    => ""
            ));
      $this->template
        ->set_layout('default')
        ->build('privilege-pica');
      
      if($this->input->post(NULL, TRUE)){
          
         if($this->input->post("sdm")){
             $sdm = "SDM";
         }
         if($this->input->post("jasa_service_part")){
             $jasa_service_part = "Jasa service dan Part";
         }
         if($this->input->post("administrasi")){
             $administrasi = "Administrasi";
         }
         if($this->input->post("marketing_promo")){
             $marketing_promo = "Marketing dan Promo";
         }
         if($this->input->post("tools")){
             $tools = "Tools";
         }
          
           $kirim = array(
              $sdm,
              $jasa_service_part,
             $administrasi,
              $marketing_promo,
              $tools );          
      $this->nbscache->put_tunggal("pica_permission", $this->input->post("privilege", TRUE), serialize($kirim));
  
      }
      
  }
  
  public function delete_setting_pica($id){
    if($this->global_models->delete("d_pica_privilege", array("id_pica_privilege" => $id)))
      redirect("outlet/setting-privilege-pica/index/list/");
    else
      redirect("outlet/setting-privilege-pica/index/list/");
  }
  
  function load_data(){
      
     $limit = "15";
    $pages = $_REQUEST["page"];
    $key = $_REQUEST["idkey"];
    $start = ($pages-1)*5;
    $query123 = "SELECT A . * , B.name AS laporan, C.name AS name_outlet
    FROM d_history AS A
    LEFT JOIN m_actifity_report AS B ON A.id_actifity_report = B.id_actifity_report
    LEFT JOIN m_outlet AS C ON B.id_outlet = C.id_outlet
    where A.kategori = {$key} and A.fix =0 
    ORDER BY  `A`.`create_date` ASC 
    LIMIT $start , {$limit} ";
   
    $data[$key] = $this->global_models->get_query($query123);
    if(is_array($data[$key])){
            $no = 1;
            foreach($data[$key] as $dt){
                        if(!$dt->problem)
                          $dt->problem = "Enter Suggest";
                        if(!$dt->corrective)
                          $dt->corrective = "Enter Suggest";         
           
                        $dtproblem = "";
                        $dtcorrective = "";
                  
                      $jks = $this->form_eksternal->form_textarea("",$dt->id_history,"");
                      
                      

                        $dtproblem = $this->form_eksternal->form_edit_textarea("problem_".$dt->id_history, 
                             site_url("outlet/history-edit/{$dt->id_history}"), 
                              $dt->problem, "type : 'textarea', rows : 8, cols : 2, submit    : 'OK', 
                              callback : function(value, settings) {sign_user('author_problem_{$dt->id_history}')}");
                        $dtcorrective = $this->form_eksternal->form_edit_textarea("corrective_".$dt->id_history, 
                              site_url("outlet/history-edit/{$dt->id_history}"), $dt->corrective, 
                              "type : 'textarea', rows : 8, cols : 2, submit    : 'OK', 
                              callback : function(value, settings) {sign_user('author_crrective_{$dt->id_history}')}");            

             $cek_list = $this->form_eksternal->form_checkbox('cek[]', 0, false, " id='cekprivilege_{$dt->id_history}' ");
             $id_style = ""; 
             $area = "
            <div class='edit' id='problem_$dt->id_history'>$dt->problem";
          // $name = nl2br($dt->name_outlet);
               $name = str_replace("\n","<br>",$dt->name_outlet);  
             $agf = "<input type='checkbox' name='cek[]' value='0' id='cekprivilege_$dt->id_history ' >";
                        
             $name1 = "
                <script>    
      $(document).ready(function() {
                          alert('haha');     
      });
   
                 </script>";
             
         $data_hasil[] = "
                       <tr id='tes_{$dt->id_history}' class='pg_{$key}'>
                        <td>{$name}
                        <td>{$dt->laporan}
                          <td>{$dt->create_date}
                          <td>{$area}
                          <td>{$dt->id_history} 
                          <td>{$dt->id_history} 
                          <td>{$dt->id_history}
                           <td>{$agf}
                          ";
                          
               }
    }
    
    echo json_encode($data_hasil);
   
    die;
  }
  function test(){
       $this->template->build('ajax_view', 
        array(
              'message'     => "",
              'url'     => base_url()."themes/srabon/",
              'menu_drop'   => $this->menu,
              'menu'        => "outlet",
              'detail'        => $detail,
              'data'        => $data,
               'pagerow'  => $pages,
              'parent'        => $parent,
              'title_table'    => "PICA All Outlet",
              'foot'    => ""
            ));
      $this->template
        ->set_layout('default')
        ->build('ajax_view');
  }


  function history_edit($id){
//    $this->debug($this->input->post(NULL, TRUE));
    $field = explode("_", $this->input->post("id", TRUE));
    if($this->input->post("value", TRUE) == "Enter suggest")
      $post = "";
    else
      $post = $this->input->post("value", TRUE);
    
    $this->global_models->update("d_history", array("id_history" => $id), 
            array($field[0] => $post));
    
    print $this->input->post("value", TRUE);
    
    die;
  }
  
  	function ajax_pic_users(){
    if (empty($_GET['term'])) exit ;
    $q = strtolower($_GET["term"]);
// remove slashes if they were magically added
    if (get_magic_quotes_gpc()) $q = stripslashes($q);

    $items = $this->moutlet->ajax_get_user_auto($q);
    $result = array();
    foreach ($items as $key=>$value) {
      if (strpos(strtolower($key), $q) !== false) {
        array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key)));
      }
      if (count($result) > 11)
        break;
    }
// json_encode is available in PHP 5.2 and above, or you can install a PECL module in earlier versions
    echo json_encode($result);
    die;
  }
  
    function post_fix(){
    
    $this->global_models->update("d_history", array("id_history" => $this->input->post("id", TRUE)), 
            array("fix" => 2, "status_view" => "Finish", "tanggal_selesai" => date("Y-m-d")));
      
      $dt = $this->global_models->get("d_history", array("id_history" => $this->input->post("id", TRUE)));
      
      $awal_time = strtotime($dt[0]->tanggal_buat);
      $selesai_time = strtotime($dt[0]->tanggal_selesai);
      $over_time = strtotime($dt[0]->due_date);
      if($dt[0]->tanggal_selesai)
        $sekarang = gregoriantojd(date("m", $selesai_time), date("d", $selesai_time), date("Y", $selesai_time));
      else
        $sekarang = gregoriantojd(date("m"), date("d"), date("Y"));

      $awal_laporan = gregoriantojd(date("m", $awal_time), date("d", $awal_time), date("Y", $awal_time));
      $lama_laporan = $sekarang - $awal_laporan;

      if($dt[0]->tanggal_selesai){
        $selesai_laporan = gregoriantojd(date("m", $selesai_time), date("d", $selesai_time), date("Y", $selesai_time));
        $lama_pengerjaan = $selesai_laporan - $awal_laporan;
        $sekarang_over = $selesai_laporan;
      }
      else{
        $lama_pengerjaan = "-";
        $sekarang_over = $sekarang;
      }

      $over_laporan = gregoriantojd(date("m", $over_time), date("d", $over_time), date("Y", $over_time));
      $lama_kelewatan =  $sekarang_over - $over_laporan;
      
      print "
        Report Date : {$dt[0]->tanggal_buat}
        <br /> Due Date : {$dt[0]->due_date}
        <br /> Finish Date : {$dt[0]->tanggal_selesai}
        <br /> Lama Laporan : {$lama_laporan} hari
        <br /> Over Due : {$lama_kelewatan} hari</span>
        <br /> PIC : ".$this->global_models->get_field("m_pic_pica", "name", array("id_pic_pica" => $dt[0]->id_pic_pica))."
            ";
    
    die;
  }
  
  function post_pic_history(){
    $this->global_models->update("d_history", array("id_history" => $this->input->post("id", TRUE)), 
            array("id_pic_users" => $this->input->post("id_pic_users", TRUE)));
    
    print $this->input->post("value", TRUE);
    
    die;
  }
  
  	function post_due_date_history(){
    $this->global_models->update("d_history", array("id_history" => $this->input->post("id", TRUE)), 
            array("due_date" => $this->input->post("due_date", TRUE)));
    
    print $this->input->post("value", TRUE);
    
    die;
  }
  
  
	public function management_organisasi($id){
//    $this->debug($this->input->post(NULL, TRUE), true);
    if(!$this->input->post(NULL, TRUE)){
      $data_detail = $this->global_models->get("m_outlet", array("id_outlet" => $id));
      $value_hidden = $this->global_models->get_array("id_users", "d_outlet_users", array("id_outlet" => $id));
      $value = array();
      $r = 1;
      $tr[] = "tr_1";
      if(is_array($value_hidden)){
        foreach($value_hidden as $vl){
          $r++;
          $tr[] = "tr_".$r;
          $temp = $this->global_models->get_field("m_users", "name", array("id_users" => $vl))." | ";
          $id_p = $this->global_models->get_field("d_user_privilege", "id_privilege", array("id_users" => $vl));
          $temp .= $this->global_models->get_field("m_privilege", "name", array("id_privilege" => $id_p));
          $value[] = $temp;
        }
      }
//      $this->debug($value);
//      $this->debug($tr, true);
      $this->template->build('management-org', 
      array('message' => "",
            'url'     => base_url()."themes/srabon/",
            'title'   => 'Management Organisasi '.$data_detail[0]->name,
            'detail'  => $data_detail,
            'menu_drop'   => $this->menu,
            'menu'        => "settings",
            'tr'        => $tr,
            'value'        => $value,
            'value_hidden' => $value_hidden,
            'foot'    => ''
          ));
      $this->template
        ->set_layout('default')
        ->build('management-org');
    }
    else{
      $pst = $this->input->post(NULL, TRUE);
      if($pst['users']){
        if(is_array($pst['users'])){
          $kirim = array();
          foreach ($pst['users'] as $plo) {
            if($plo != 0)
              $kirim[] = $plo;
          }
        }
        if($this->moutlet->insert_user_outlet($pst['id_detail'], $kirim))
          redirect ("outlet/index/list/sukses");
        else
          redirect ("outlet/index/list/filed");
      }
    }
  }
	public function pic_users($id){
//    $this->debug($this->input->post(NULL, TRUE), true);
    if(!$this->input->post(NULL, TRUE)){
      $data_detail = $this->global_models->get("m_outlet", array("id_outlet" => $id));
      $value_hidden = $this->global_models->get_array("id_users", "d_pic_users", array("id_outlet" => $id));
      $value = array();
      $r = 1;
      $tr[] = "tr_1";
      if(is_array($value_hidden)){
        $r = 2;
        foreach($value_hidden as $vl){
          $tr[] = "tr_".$r++;
          $temp = $this->global_models->get_field("m_users", "name", array("id_users" => $vl))." | ";
          $id_p = $this->global_models->get_field("d_user_privilege", "id_privilege", array("id_users" => $vl));
          $temp .= $this->global_models->get_field("m_privilege", "name", array("id_privilege" => $id_p));
          $value[] = $temp;
        }
      }
//      $this->debug($value);
//      $this->debug($value_hidden, true);
      $this->template->build('pic-users', 
      array('message' => "",
            'url'     => base_url()."themes/srabon/",
            'title'   => 'PIC '.$data_detail[0]->name,
            'detail'  => $data_detail,
            'menu_drop'   => $this->menu,
            'menu'        => "settings",
            'tr'        => $tr,
            'value'        => $value,
            'value_hidden' => $value_hidden,
            'foot'    => ''
          ));
      $this->template
        ->set_layout('default')
        ->build('pic-users');
    }
    else{
      $pst = $this->input->post(NULL, TRUE);
      if($pst['users']){
        if(is_array($pst['users'])){
          $kirim = array();
          foreach ($pst['users'] as $plo) {
            if($plo != 0)
              $kirim[] = $plo;
          }
        }
        if($this->moutlet->insert_user_pic($pst['id_detail'], $kirim))
          redirect ("outlet/index/list/sukses");
        else
          redirect ("outlet/index/list/filed");
      }
    }
  }
	public function add_new($id = 0, $pesan = "hal"){
   
    $this->template->title('Sistem', "Outlet Edit");
    if($id > 0){
      $data_detail = $this->global_models->get("m_outlet", array("id_outlet" => $id));
//      $this->debug($data_detail, true);
    }
    else{
      $data_detail[0]->id_outlet = 0;
      $data_detail[0]->name = "";
      $data_detail[0]->email = "";
      $data_detail[0]->telp = "";
      $data_detail[0]->alamat = "";
      $data_detail[0]->kota = "";
      $data_detail[0]->kodepos = "";
      $data_detail[0]->pos = "";
	  $data_detail[0]->own = "";
    }
    if(!$this->input->post(NULL, TRUE)){
      $this->template->build('add-new', 
        array('message' => $pesan,
              'url'     => base_url()."themes/srabon/",
              'title'   => 'Add Outlet',
              'detail'  => $data_detail,
              'menu_drop'   => $this->menu,
              'menu'        => "settings",
              'foot'    => '
                <script>
                  $(function () {
                    // validate signup form on keyup and submit
                    var validator = $("#formoutlet").validate({
                        rules: {
                            name: "required",
                            telp: "required",
                            alamat: "required",
                            kota: "required",
                            email: "required"
                        },
                        messages: {
                            name: "Enter the name",
                            telp: "Enter telphone",
                            alamat: "Enter your address",
                            kota: "Enter your city",
                            email: "Enter your email"
                        }
                    });
                });
                </script>
                '
            ));
      $this->template
        ->set_layout('default')
        ->build('add-new');
    }
    else{
      $pst = $this->input->post();
      if($this->input->post("id_detail", TRUE)){
//          if($this->input->post("status", TRUE)){
//              $id_status_outlet = 0;
//          }else{
//              $id_status_outlet = 1;
//          }
        $data_detail_pos = $this->global_models->get("m_outlet", array("id_outlet" => $this->input->post("id_detail", TRUE)));
        if($this->session->userdata('id') == 1){
          $pos = $this->input->post("pos", TRUE);
        }else{
          $pos = $data_detail_pos[0]->pos;
        }
		 if($this->input->post("own", TRUE)){
          $own = "1";
        }else{
          $own = "0";
        }
        
        if(!$pst['no_outlet']){
          $this->session->set_flashdata('extent', 'Nomor Outlet Belum di Set Harap Lakukan Perubahan');
        }
        else if($this->global_models->get_field("m_outlet", "no_outlet", array("no_outlet" => $pst['no_outlet'], "id_outlet <>" => $pst['id_detail']))){
          $this->session->set_flashdata('extent', 'Nomor Outlet Tidak Boleh Sama Harap Lakukan Perubahan');
          $pst['no_outlet'] = "";
        }
        
        $kirim = array(
              "name"                  =>  $this->input->post("name", TRUE),
              "pos"                   =>  $pos,
              "telp"                  =>  $this->input->post("telp", TRUE),
              "alamat"                =>  $this->input->post("alamat", TRUE),
              "kota"                  =>  $this->input->post("kota", TRUE),
              "kodepos"               =>  $this->input->post("kodepos", TRUE),
              "email"                 =>  $this->input->post("email", TRUE),
              "own"                   =>  $own,
              "id_status_outlet"      =>  $this->input->post("status", TRUE),
              "no_outlet"             => $pst['no_outlet'],
              "ka_outlet"             => $pst['ka_outlet'],
              "owner_outlet"          => $pst['owner_outlet'],
              "hp_owner"              => $pst['hp_owner'],
              "grand_launching"       => $pst['grand_launching'],
              "edc_mandiri"           => $pst['edc_mandiri'],
              "system_pos"            => $pst['system_pos'],
              "jenis_database"        => $pst['jenis_database'],
              "db_location"           => $pst['db_location'],
              "brand_hardware"        => $pst['brand_hardware'],
              "internet_status"       => $pst['internet_status'],
              "internet_connection"   => $pst['internet_connection'],
              "update_by_users"       =>  $this->session->userdata('id')
          );
       
        $hasil_in = $this->global_models->update("m_outlet", array("id_outlet" => $this->input->post("id_detail", TRUE)), $kirim);
        if($hasil_in){
          $this->session->set_flashdata('success', 'Data tersimpan');
        }
        else{
          $this->session->set_flashdata('notice', 'Data gagal disimpan');
        }
        redirect ("outlet/index/list");
      }
      else{
        $pst = $this->input->post(NULL, TRUE);
//        $pst = $pst['addressform']['addressform'][0];
        if($pst['name']){
             if($this->input->post("status", TRUE)){
              $id_status_outlet = 0;
            }else{
              $id_status_outlet = 1;
            }
			 if($this->input->post("own", TRUE)){
          $own = "1";
        }else{
          $own = "0";
        }
          if(!$pst['no_outlet']){
            $this->session->set_flashdata('extent', 'Nomor Outlet Belum di Set Harap Lakukan Perubahan');
          }
          else if($this->global_models->get_field("m_outlet", "no_outlet", array("no_outlet" => $pst['no_outlet']))){
            $this->session->set_flashdata('extent', 'Nomor Outlet Tidak Boleh Sama Harap Lakukan Perubahan');
            $pst['no_outlet'] = "";
          }
          
          $kirim = array(
              "name"                  =>  $pst['name'],
              "pos"                   =>  $pst['pos'],
              "telp"                  =>  $pst['telp'],
              "alamat"                =>  $pst['alamat'],
              "kota"                  =>  $pst['kota'],
              "kodepos"               =>  $pst['kodepos'],
              "email"                 =>  $pst['email'],
              "own"                   =>  $own,
              "create_by_users"       =>  $this->session->userdata('id'),
              "create_date"           =>  date("Y-m-d H:i:s"),
               "id_status_outlet"     =>  $this->input->post("status", TRUE),
              "no_outlet"             => $pst['no_outlet'],
              "ka_outlet"             => $pst['ka_outlet'],
              "owner_outlet"          => $pst['owner_outlet'],
              "hp_owner"              => $pst['hp_owner'],
              "grand_launching"       => $pst['grand_launching'],
              "edc_mandiri"           => $pst['edc_mandiri'],
              "system_pos"            => $pst['system_pos'],
              "jenis_database"        => $pst['jenis_database'],
              "db_location"           => $pst['db_location'],
              "brand_hardware"        => $pst['brand_hardware'],
              "internet_status"       => $pst['internet_status'],
              "internet_connection"   => $pst['internet_connection'],
              "update_by_users"       =>  $this->session->userdata('id')
          );
          if($this->global_models->insert("m_outlet", $kirim)){
            $this->session->set_flashdata('success', 'Data tersimpan');
          }
          else{
            $this->session->set_flashdata('notice', 'Data gagal disimpan');
          }
        }
        else{
          $this->session->set_flashdata('notice', 'Data gagal disimpan');
        }
      }
      redirect ("outlet/index/list");
    }
  }
  
public function pos($id = 0, $pesan = "hal"){
   
        $pos = $this->global_models->get_query("select COUNT(pos) AS total FROM m_outlet where pos != '' AND last_console IS NOT NULL AND id_status_outlet = 0 ");
       // $pos_data = $this->global_models->get_query("select pos FROM m_outlet where pos != '' ");
  
    $this->template->title('Sistem', "Outlet Edit");
    if(!$this->input->post(NULL, TRUE)){
      $this->template->build('main-pos', 
        array('message' => $pesan,
              'url'     => base_url()."themes/srabon/",
              'title'   => 'POS Outlet',
              'menu_drop'   => $this->menu,
              'menu'        => "settings",
            ));
      $this->template
        ->set_layout('default')
        ->build('main-pos');
    }
    else{
      $pst = $this->input->post(NULL, TRUE);
   
     $set_ses = array(
          "outlet_pos_number"  => 0,
          "outlet_pos_total"   => 0,
      );
     $this->session->set_userdata($set_ses);
      $this->template->build('eksekusi-pos', 
        array('message' => $pesan,
              'url'     => base_url()."themes/srabon/",
              'title'   => 'POS Outlet',
              'total_pos' =>$pos[0]->total,
              'field_tanggal' => $pst['tanggal'],
              'menu_drop'   => $this->menu,
              'menu'        => "settings",
            'persent'     => (int)($this->session->userdata("outlet_pos_number")/$this->session->userdata("outlet_pos_total") * 100)
        
            ));
      $this->template
        ->set_layout('default')
        ->build('eksekusi-pos');
       
    }
  }
  
  function ajax_eksekusi_db_pos($total_pos_outlet,$tgl40){
   
    $fix_tgl = str_replace("_", "-", $tgl40);
    $no_db = $this->session->userdata("outlet_pos_number");
    $pos = $this->global_models->get_query("select name,pos FROM m_outlet where pos != '' ");
    $db_cuy = $pos[$no_db]->pos;
    $db_outlet_name = $pos[$no_db]->name;
      $data_outlet = $this->global_models->get("m_outlet", array("pos" => $db_cuy));
      $id_outlet = $data_outlet[0]->id_outlet; 
       $tgl = strtotime($fix_tgl);
      $date_bulan =  date("n", $tgl);
     $date_year =  date("Y", $tgl);
    $date_day =  date("j", $tgl); 
     
	 $data_report_detail_1 = $this->global_models->get_query("select id_actifity_report FROM m_actifity_report where id_outlet =  $id_outlet AND month = $date_bulan AND year = $date_year");
    if(!$data_report_detail_1) {
      $this->global_models->insert("m_actifity_report", 
              array(
                 "id_outlet" =>  $id_outlet,
                  "name"      =>  "Laporan ".date("F",$tgl)." ".$date_year,
                  "month"     =>  $date_bulan,
                  "day_in_month"     =>  date("t",$tgl),
                  "year"      =>  $date_year,
                  "create_by_users" =>  1,
                  "create_date" =>  date("Y-m-d H:i:s"),
                  "update_by_users" =>  1
                  ));          
    }
    
   // $data_report =  $this->global_models->get("m_actifity_report", array("id_outlet" => $id_outlet, "month" => $date_bulan, 'year' => $date_year));
    $data_report1 = $this->global_models->get_query("select id_actifity_report FROM m_actifity_report where id_outlet =  $id_outlet AND month = $date_bulan AND year = $date_year");
    
    $id_actifity_report = $data_report1[0]->id_actifity_report;
    $day_actifity_report =  $this->global_models->get("d_day_actifity_report", array("id_actifity_report" => $id_actifity_report, "tanggal" => $date_day));
   $id_day_actifity_report = $day_actifity_report[0]->id_day_actifity_report;
   
   $data = $this->get_web_page("192.168.2.14/cgi-bin/iframeots.exe/waProcess?db={$db_cuy}&dt={$fix_tgl}");
   $cek_data = strpos($data,"[tmi]");
 if($cek_data!==false)
  {
   $data1 = explode("[tmi]", $data); 
      $data2 = explode(";", $data1[1]);  
     if(empty($data2[0])){
       $service = "";
     }else{
       $service = str_replace("\r\n", "", $data2[0]);
     }
     if(empty($data2[1])){
       $belanja = "";
     }else{
       $belanja = str_replace("\r\n", "", $data2[1]);
     }
     if(empty($data2[2])){
       $service_belanja = "";
     }else{
       $service_belanja = str_replace("\r\n", "", $data2[2]);
     }
     if(empty($data2[3])){
       $p_service = "";
     }else{
       $p_service = str_replace("\r\n", "", $data2[3]);
     }
     if(empty($data2[4])){
       $p_belanja = "";
     }else{
       $p_belanja = str_replace("\r\n", "", $data2[4]);
     }
     if(empty($data2[5])){
       $p_service_plus = "";
     }else{
       $p_service_plus = str_replace("\r\n", "", $data2[5]);
     }
     if(empty($data2[6])){
       $p_belanja_plus = "";
     }else{
       $p_belanja_plus = str_replace("\r\n", "", $data2[6]);
     }
     if(empty($data2[7])){
       $total_hpp = "";
     }else{
       $total_hpp = str_replace("\r\n", "", $data2[7]);
     }
     if(empty($service) AND empty($belanja) AND empty($service_belanja) AND empty($p_service) AND empty($p_belanja) AND empty($p_service_plus) AND empty($p_belanja_plus) AND empty($total_hpp)){
       $pesan = "Data Outlet ".$db_outlet_name." Tanggal ".$fix_tgl." | Kosong ";
      $log_pos_kosong = $pesan.$db_cuy." ;#".date("Y-m-d H:i:s");
      $this->nbscache->put_tunggal_sql("log_pos_kosong",$log_pos_kosong);
     }else{
				if(empty($id_day_actifity_report)){
			  $kirim = array(
					  "service"               =>  $service,
					  "belanja"               =>  $belanja,
					  "service_belanja"       =>  $service_belanja,
					  "p_service"             =>  $p_service,
					  "p_belanja"             =>  $p_belanja,
					  "p_service_plus"        => $p_service_plus,
					  "p_belanja_plus"        =>  $p_belanja_plus,
					  "total_hpp"             => $total_hpp,
					  "id_actifity_report"    => $id_actifity_report,
					  "tanggal"               =>  $date_day,
					  "create_by_users"       =>  $this->session->userdata('id'),
					  "create_date"           =>  date("Y-m-d H:i:s"),
					  "update_by_users"       =>  $this->session->userdata('id')
				  );
			  $this->global_models->insert("d_day_actifity_report", $kirim);
			  $pesan = "Insert Outlet ".$db_outlet_name;
		   }else{
			  $kirim = array(
					 "service"               =>  $service,
					  "belanja"               =>  $belanja,
					  "service_belanja"       =>  $service_belanja,
					  "p_service"             =>  $p_service,
					  "p_belanja"             =>  $p_belanja,
					  "p_service_plus"        => $p_service_plus,
					  "p_belanja_plus"        =>  $p_belanja_plus,
					  "total_hpp"             => $total_hpp,
					  "id_actifity_report"    => $id_actifity_report,
					  "tanggal"               =>  $date_day,
					  "update_by_users"       =>  $this->session->userdata('id')
				  );
			   
				$hasil_in = $this->global_models->update("d_day_actifity_report", array("id_day_actifity_report" => $id_day_actifity_report), $kirim);
			   
			 $pesan = "Update Outlet ".$db_outlet_name;
		   }
	 }
   
  }else{
   $pesan = $db_outlet_name;
   $log_pos = $pesan." | Gagal ".$db_cuy;
   $this->nbscache->put_tunggal_sql("log_pos",$log_pos);
  }  
   
    if($this->session->userdata("outlet_pos_number") > $total_pos_outlet){
      $nomor = $total_pos_outlet;
    }else{
      $nomor = $this->session->userdata("outlet_pos_number") + 1;
    }
      
      $set_ses = array(
          "outlet_pos_number"  => $nomor,
          "total_pos_outlet"   => $total_pos_outlet,
      );
      
      $this->session->set_userdata($set_ses);
      $hasil = array(
          "percent" => Ceil($nomor/$total_pos_outlet * 100),
          "n"       => $nomor,
          "rn"      => $total_pos_outlet,
          "note"    => $pesan,
      );
      print json_encode($hasil);
      die;
    
  }
  
  public function pos_select($id = 0, $pesan = "hal"){
   
        $pos_2 = $this->global_models->get_query("select * FROM m_outlet where pos != '' ORDER BY name ASC");
       // $pos = $this->global_models->get_query("select COUNT(pos) AS total FROM m_outlet where pos != '' ");
      if(is_array($pos_2)){
         
          foreach ($pos_2 as $value) {
          //  print_r($value); die;
           $pos_data[$value->pos] = $value->name;
       
          }
      }
    $this->template->title('Sistem', "Outlet Edit");
    if(!$this->input->post(NULL, TRUE)){
      $this->template->build('main-pos', 
        array('message' => $pesan,
              'url'     => base_url()."themes/srabon/",
              'title'   => 'POS Outlet',
              'menu_drop'   => $this->menu,
             'pos_data'   => $pos_data,
              'menu'        => "settings",
            ));
      $this->template
        ->set_layout('default')
        ->build('main-pos-select');
    }
    else{
      $pst = $this->input->post(NULL, TRUE);
      $nm_outlet = $pst['name_outlet'];
     $total_angka = count($nm_outlet);
     $set_ses = array(
          "outlet_pos_number"  => 0,
          "outlet_pos_total"   => 0,
         
      );
     $this->session->set_userdata($set_ses);
     
     $data_pos_name = array(
         "name_pos_outlet" =>serialize($nm_outlet),
     );
     
     $this->session->set_userdata($data_pos_name);
     
      $this->template->build('eksekusi-pos-select', 
        array('message' => $pesan,
              'url'     => base_url()."themes/srabon/",
              'title'   => 'POS Outlet',
              'total_pos' => $total_angka,
               "name_ot"   => $nm_outlet,
              'field_tanggal' => $pst['tanggal'],
              'menu_drop'   => $this->menu,
              'menu'        => "settings",
            'persent'     => Ceil($this->session->userdata("outlet_pos_number")/$this->session->userdata("outlet_pos_total") * 100)
        
            ));
      $this->template
        ->set_layout('default')
        ->build('eksekusi-pos-select');
       
    }
  }
  
  public function pos_option($id = 0, $pesan = "hal"){
   
        $pos = $this->global_models->get_query("select COUNT(pos) AS total FROM m_outlet where pos != '' ");
        $pos_2 = $this->global_models->get_query("select * FROM m_outlet where pos != '' ");
        //print_r($pos_2); die;
         if(is_array($pos_2)){
         $pos_data[0] = "- Pilih -";
          foreach ($pos_2 as $value) {
          //  print_r($value); die;
           $pos_data[$value->pos] = $value->name." --- ".$value->pos;
       
          }
        }
  
    $this->template->title('Sistem', "Outlet Edit");
    if(!$this->input->post(NULL, TRUE)){
      $this->template->build('main-pos', 
        array('message' => $pesan,
              'url'     => base_url()."themes/srabon/",
              'title'   => 'POS Outlet',
              'menu_drop'   => $this->menu,
             'pos_data'   => $pos_data,
              'menu'        => "settings",
            ));
      $this->template
        ->set_layout('default')
        ->build('main-pos-option');
    }
    else{
      $pst = $this->input->post(NULL, TRUE);
      $data_outlet = $this->global_models->get("m_outlet", array("pos" => $pst['pos_data']));
      $id_outlet = $data_outlet[0]->id_outlet;
      
//      $start = "2014-04-01";
      $start = $this->global_models->get_field("m_outlet", "last_console", array("id_outlet" => $id_outlet));
//      $end = "2014-04-30";
      $end = $pst['tanggal'];
      
      $start_time = strtotime($start);
      $end_time = strtotime($end);
      
      if($end_time <= $start_time){
        $start = $pst['tanggal'];
//        $start = "2014-04-01";
        $start_time = strtotime($start);
      }
      
      $ct = strtotime("2014-02-22");
      $ct2 = strtotime("2014-02-23");
      $aday = $ct2 - $ct;
      
      $start_time -= ($aday * 7);
      
      for($r = $start_time ; $r <= $end_time ; $r += $aday){
//        $this->debug(date("Y-m-d", $r));
        
        $tanggal_fix = date("Y-m-d", $r);
        
        $tgl = strtotime($tanggal_fix);
        $date_bulan =  date("n", $tgl);
        $date_year =  date("Y", $tgl);
        $date_day =  date("j", $tgl); 

        $data_report =  $this->global_models->get("m_actifity_report", array("id_outlet" => $id_outlet, "month" => $date_bulan, 'year' => $date_year));

        $id_actifity_report = $data_report[0]->id_actifity_report;
        $day_actifity_report =  $this->global_models->get("d_day_actifity_report", array("id_actifity_report" => $id_actifity_report, "tanggal" => $date_day));
        $id_day_actifity_report = $day_actifity_report[0]->id_day_actifity_report;// die;
  //   print "http://192.168.2.141/cgi-bin/iframeots.exe/waProcess?db={$pst['pos_data']}&dt={$pst['tanggal']}";die;
        $data = $this->get_web_page("192.168.2.14/cgi-bin/iframeots.exe/waProcess?db={$pst['pos_data']}&dt={$tanggal_fix}");
        $cek_data = strpos($data,"[tmi]");
        if($cek_data!==false){
            $data1 = explode("[tmi]", $data);  
             $data2 = explode(";", $data1[1]);    

            if(empty($data2[0])){
              $service = "";
            }else{
              $service = str_replace("\r\n", "", $data2[0]);
            }
            if(empty($data2[1])){
              $belanja = "";
            }else{
              $belanja = str_replace("\r\n", "", $data2[1]);
            }
            if(empty($data2[2])){
              $service_belanja = "";
            }else{
              $service_belanja = str_replace("\r\n", "", $data2[2]);
            }
            if(empty($data2[3])){
              $p_service = "";
            }else{
              $p_service = str_replace("\r\n", "", $data2[3]);
            }
            if(empty($data2[4])){
              $p_belanja = "";
            }else{
              $p_belanja = str_replace("\r\n", "", $data2[4]);
            }
            if(empty($data2[5])){
              $p_service_plus = "";
            }else{
              $p_service_plus = str_replace("\r\n", "", $data2[5]);
            }
            if(empty($data2[6])){
              $p_belanja_plus = "";
            }else{
              $p_belanja_plus = str_replace("\r\n", "", $data2[6]);
            }
            if(empty($data2[7])){
              $total_hpp = "";
            }else{
              $total_hpp = str_replace("\r\n", "", $data2[7]);
            }

          if(empty($service) AND empty($belanja) AND empty($service_belanja) AND empty($p_service) AND empty($p_belanja) AND empty($p_service_plus) AND empty($p_belanja_plus) AND empty($total_hpp)){
          $pesan = "Data Outlet ".$data_outlet[0]->name." Tanggal ".$tanggal_fix." | Kosong ";
             $log_pos_kosong = $pesan.$pst['pos_data']." ;#".date("Y-m-d H:i:s");
             $this->nbscache->put_tunggal_sql("log_pos_kosong",$log_pos_kosong);
          }else{
             if(empty($id_day_actifity_report)){
               $kirim = array(
                   "service"               =>  $service,
                   "belanja"               =>  $belanja,
                   "service_belanja"       =>  $service_belanja,
                   "p_service"             =>  $p_service,
                   "p_belanja"             =>  $p_belanja,
                   "p_service_plus"        => $p_service_plus,
                   "p_belanja_plus"        =>  $p_belanja_plus,
                   "total_hpp"             => $total_hpp,
                   "id_actifity_report"    => $id_actifity_report,
                   "tanggal"               =>  $date_day,
                   "create_by_users"       =>  $this->session->userdata('id'),
                   "create_date"           =>  date("Y-m-d H:i:s"),
                   "update_by_users"       =>  $this->session->userdata('id')
                 );
               $this->global_models->insert("d_day_actifity_report", $kirim);
               $pesan = "insert";
              }else{
               $kirim = array(
                  "service"               =>  $service,
                   "belanja"               =>  $belanja,
                   "service_belanja"       =>  $service_belanja,
                   "p_service"             =>  $p_service,
                   "p_belanja"             =>  $p_belanja,
                   "p_service_plus"        => $p_service_plus,
                   "p_belanja_plus"        =>  $p_belanja_plus,
                   "total_hpp"             => $total_hpp,
                   "id_actifity_report"    => $id_actifity_report,
                   "tanggal"               =>  $date_day,
                   "update_by_users"       =>  $this->session->userdata('id')
                 );

               $hasil_in = $this->global_models->update("d_day_actifity_report", array("id_day_actifity_report" => $id_day_actifity_report), $kirim);

              $pesan = "update";
              }
              $this->global_models->update("m_outlet", array("id_outlet" => $id_outlet), array("last_console" => $tanggal_fix));
          }

         }else{
           $pesan = "failed";
           $log_pos = $pesan." outlet ".$data_outlet[0]->name." tanggal ".$tanggal_fix." POS ".$data_outlet[0]->pos;
          $this->nbscache->put_tunggal_sql("log_pos",$log_pos);

         }
      }
      
    /*  $pos = $this->global_models->get_query("select pos FROM m_outlet where pos != '' ");
         if(is_array($pos)){
         $pos_data[0] = "- Pilih -";
          foreach ($pos as $key => $value) {
           $pos_data[$value->pos] = $value->pos;
       
          }
        } */
      $this->template->build('main-pos-option', 
        array('message' => $pesan,
            'data' => $data,
              'url'     => base_url()."themes/srabon/",
              'title'   => 'POS Outlet',
              'pos_data'  => $pos_data,
              'field_pos' =>$pst['pos_data'],
              'field_tanggal' => $pst['tanggal'],
              'menu_drop'   => $this->menu,
              'menu'        => "settings",
            ));
      $this->template
        ->set_layout('default')
        ->build('main-pos-option');
       
    }
  }
  
  public function pos_option_ext($id = 0, $pesan = "hal"){
   
        $pos = $this->global_models->get_query("select COUNT(pos) AS total FROM m_outlet where pos != '' ");
        $pos_2 = $this->global_models->get_query("select * FROM m_outlet where pos != '' ");
        //print_r($pos_2); die;
         if(is_array($pos_2)){
         $pos_data[0] = "- Pilih -";
          foreach ($pos_2 as $value) {
          //  print_r($value); die;
           $pos_data[$value->pos] = $value->name." --- ".$value->pos;
       
          }
        }
  
    $this->template->title('Sistem', "Outlet Edit");
    if(!$this->input->post(NULL, TRUE)){
      $this->template->build('main-pos', 
        array('message' => $pesan,
              'url'     => base_url()."themes/srabon/",
              'title'   => 'POS Outlet',
              'menu_drop'   => $this->menu,
             'pos_data'   => $pos_data,
              'menu'        => "settings",
            ));
      $this->template
        ->set_layout('default')
        ->build('main-pos-option');
    }
    else{
      $pst = $this->input->post(NULL, TRUE);
      $data_outlet = $this->global_models->get("m_outlet", array("pos" => $pst['pos_data']));
      $id_outlet = $data_outlet[0]->id_outlet;
      
//      $start = $this->global_models->get_field("m_outlet", "last_console", array("id_outlet" => $id_outlet));
      $start = "2014-04-01";
//      $end = "2014-01-31";
      $end = $pst['tanggal'];
      
      $start_time = strtotime($start);
      $end_time = strtotime($end);
      
      if($end_time <= $start_time){
        $start = $pst['tanggal'];
//        $start = "2014-01-01";
        $start_time = strtotime($start);
      }
      
      $ct = strtotime("2014-02-22");
      $ct2 = strtotime("2014-02-23");
      $aday = $ct2 - $ct;
      
      $start_time -= ($aday * 7);
      
      for($r = $start_time ; $r <= $end_time ; $r += $aday){
//        $this->debug(date("Y-m-d", $r));
        
        $tanggal_fix = date("Y-m-d", $r);
        
        $tgl = strtotime($tanggal_fix);
        $date_bulan =  date("n", $tgl);
        $date_year =  date("Y", $tgl);
        $date_day =  date("j", $tgl); 

        $data_report =  $this->global_models->get("m_actifity_report", array("id_outlet" => $id_outlet, "month" => $date_bulan, 'year' => $date_year));

        $id_actifity_report = $data_report[0]->id_actifity_report;
        $day_actifity_report =  $this->global_models->get("d_day_actifity_report", array("id_actifity_report" => $id_actifity_report, "tanggal" => $date_day));
        $id_day_actifity_report = $day_actifity_report[0]->id_day_actifity_report;// die;
  //   print "http://192.168.2.141/cgi-bin/iframeots.exe/waProcess?db={$pst['pos_data']}&dt={$pst['tanggal']}";die;
        $data = $this->get_web_page("192.168.2.14/cgi-bin/iframeots.exe/waProcess?db={$pst['pos_data']}&dt={$tanggal_fix}");
        $cek_data = strpos($data,"[tmi]");
        if($cek_data!==false){
            $data1 = explode("[tmi]", $data);  
             $data2 = explode(";", $data1[1]);    

            if(empty($data2[0])){
              $service = "";
            }else{
              $service = str_replace("\r\n", "", $data2[0]);
            }
            if(empty($data2[1])){
              $belanja = "";
            }else{
              $belanja = str_replace("\r\n", "", $data2[1]);
            }
            if(empty($data2[2])){
              $service_belanja = "";
            }else{
              $service_belanja = str_replace("\r\n", "", $data2[2]);
            }
            if(empty($data2[3])){
              $p_service = "";
            }else{
              $p_service = str_replace("\r\n", "", $data2[3]);
            }
            if(empty($data2[4])){
              $p_belanja = "";
            }else{
              $p_belanja = str_replace("\r\n", "", $data2[4]);
            }
            if(empty($data2[5])){
              $p_service_plus = "";
            }else{
              $p_service_plus = str_replace("\r\n", "", $data2[5]);
            }
            if(empty($data2[6])){
              $p_belanja_plus = "";
            }else{
              $p_belanja_plus = str_replace("\r\n", "", $data2[6]);
            }
            if(empty($data2[7])){
              $total_hpp = "";
            }else{
              $total_hpp = str_replace("\r\n", "", $data2[7]);
            }

          if(empty($service) AND empty($belanja) AND empty($service_belanja) AND empty($p_service) AND empty($p_belanja) AND empty($p_service_plus) AND empty($p_belanja_plus) AND empty($total_hpp)){
          $pesan = "Data Outlet ".$data_outlet[0]->name." Tanggal ".$tanggal_fix." | Kosong ";
             $log_pos_kosong = $pesan.$pst['pos_data']." ;#".date("Y-m-d H:i:s");
             $this->nbscache->put_tunggal_sql("log_pos_kosong",$log_pos_kosong);
          }else{
             if(empty($id_day_actifity_report)){
               $kirim = array(
                   "service"               =>  $service,
                   "belanja"               =>  $belanja,
                   "service_belanja"       =>  $service_belanja,
                   "p_service"             =>  $p_service,
                   "p_belanja"             =>  $p_belanja,
                   "p_service_plus"        => $p_service_plus,
                   "p_belanja_plus"        =>  $p_belanja_plus,
                   "total_hpp"             => $total_hpp,
                   "id_actifity_report"    => $id_actifity_report,
                   "tanggal"               =>  $date_day,
                   "create_by_users"       =>  $this->session->userdata('id'),
                   "create_date"           =>  date("Y-m-d H:i:s"),
                   "update_by_users"       =>  $this->session->userdata('id')
                 );
               $this->global_models->insert("d_day_actifity_report", $kirim);
               $pesan = "insert";
              }else{
               $kirim = array(
                  "service"               =>  $service,
                   "belanja"               =>  $belanja,
                   "service_belanja"       =>  $service_belanja,
                   "p_service"             =>  $p_service,
                   "p_belanja"             =>  $p_belanja,
                   "p_service_plus"        => $p_service_plus,
                   "p_belanja_plus"        =>  $p_belanja_plus,
                   "total_hpp"             => $total_hpp,
                   "id_actifity_report"    => $id_actifity_report,
                   "tanggal"               =>  $date_day,
                   "update_by_users"       =>  $this->session->userdata('id')
                 );

               $hasil_in = $this->global_models->update("d_day_actifity_report", array("id_day_actifity_report" => $id_day_actifity_report), $kirim);

              $pesan = "update";
              }
              $this->global_models->update("m_outlet", array("id_outlet" => $id_outlet), array("last_console" => $tanggal_fix));
          }

         }else{
           $pesan = "failed";
           $log_pos = $pesan." outlet ".$data_outlet[0]->name." tanggal ".$tanggal_fix." POS ".$data_outlet[0]->pos;
          $this->nbscache->put_tunggal_sql("log_pos",$log_pos);

         }
      }
      
    /*  $pos = $this->global_models->get_query("select pos FROM m_outlet where pos != '' ");
         if(is_array($pos)){
         $pos_data[0] = "- Pilih -";
          foreach ($pos as $key => $value) {
           $pos_data[$value->pos] = $value->pos;
       
          }
        } */
      $this->template->build('main-pos-option', 
        array('message' => $pesan,
            'data' => $data,
              'url'     => base_url()."themes/srabon/",
              'title'   => 'POS Outlet',
              'pos_data'  => $pos_data,
              'field_pos' =>$pst['pos_data'],
              'field_tanggal' => $pst['tanggal'],
              'menu_drop'   => $this->menu,
              'menu'        => "settings",
            ));
      $this->template
        ->set_layout('default')
        ->build('main-pos-option');
       
    }
  }
  
  function ajax_eksekusi_db_pos_select($total_pos_outlet,$tgl40){
   
    $fix_tgl = str_replace("_", "-", $tgl40);
    $no_db = $this->session->userdata("outlet_pos_number");
   $data_out = unserialize($this->session->userdata("name_pos_outlet"));
    
    $db_cuy = $data_out[$no_db];
      $data_outlet = $this->global_models->get("m_outlet", array("pos" => $db_cuy));
      $id_outlet = $data_outlet[0]->id_outlet; 
       $tgl = strtotime($fix_tgl);
      $date_bulan =  date("n", $tgl);
      
     $date_year =  date("Y", $tgl);
    $date_day =  date("j", $tgl); 
    
    $data_report_detail_1 = $this->global_models->get_query("select id_actifity_report FROM m_actifity_report where id_outlet =  $id_outlet AND month = $date_bulan AND year = $date_year");
    if(!$data_report_detail_1) {
      $this->global_models->insert("m_actifity_report", 
              array(
                 "id_outlet" =>  $id_outlet,
                  "name"      =>  "Laporan ".date("F",$tgl)." ".$date_year,
                  "month"     =>  $date_bulan,
                  "day_in_month"     =>  date("t",$tgl),
                  "year"      =>  $date_year,
                  "create_by_users" =>  1,
                  "create_date" =>  date("Y-m-d H:i:s"),
                  "update_by_users" =>  1
                  ));          
    }
    
   // $data_report =  $this->global_models->get("m_actifity_report", array("id_outlet" => $id_outlet, "month" => $date_bulan, 'year' => $date_year));
    $data_report1 = $this->global_models->get_query("select id_actifity_report FROM m_actifity_report where id_outlet =  $id_outlet AND month = $date_bulan AND year = $date_year");
    
    $id_actifity_report = $data_report1[0]->id_actifity_report;
    $day_actifity_report =  $this->global_models->get("d_day_actifity_report", array("id_actifity_report" => $id_actifity_report, "tanggal" => $date_day));
   $id_day_actifity_report = $day_actifity_report[0]->id_day_actifity_report;
   
   $data = $this->get_web_page("192.168.2.14/cgi-bin/iframeots.exe/waProcess?db={$db_cuy}&dt={$fix_tgl}");
   
   $cek_data = strpos($data,"[tmi]");
 if($cek_data!==false)
  {
   $data1 = explode("[tmi]", $data); 
      $data2 = explode(";", $data1[1]);  
     if(empty($data2[0])){
       $service = "";
     }else{
       $service = str_replace("\r\n", "", $data2[0]);
     }
     if(empty($data2[1])){
       $belanja = "";
     }else{
       $belanja = str_replace("\r\n", "", $data2[1]);
     }
     if(empty($data2[2])){
       $service_belanja = "";
     }else{
       $service_belanja = str_replace("\r\n", "", $data2[2]);
     }
     if(empty($data2[3])){
       $p_service = "";
     }else{
       $p_service = str_replace("\r\n", "", $data2[3]);
     }
     if(empty($data2[4])){
       $p_belanja = "";
     }else{
       $p_belanja = str_replace("\r\n", "", $data2[4]);
     }
     if(empty($data2[5])){
       $p_service_plus = "";
     }else{
       $p_service_plus = str_replace("\r\n", "", $data2[5]);
     }
     if(empty($data2[6])){
       $p_belanja_plus = "";
     }else{
       $p_belanja_plus = str_replace("\r\n", "", $data2[6]);
     }
     if(empty($data2[7])){
       $total_hpp = "";
     }else{
       $total_hpp = str_replace("\r\n", "", $data2[7]);
     }
     if(empty($service) AND empty($belanja) AND empty($service_belanja) AND empty($p_service) AND empty($p_belanja) AND empty($p_service_plus) AND empty($p_belanja_plus) AND empty($total_hpp)){
       $pesan = "Data Outlet ".$data_outlet[0]->name." Tanggal ".$fix_tgl." | Kosong ";
      $log_pos_kosong = $pesan.$db_cuy." ;#".date("Y-m-d H:i:s");;
      $this->nbscache->put_tunggal_sql("log_pos_kosong",$log_pos_kosong);
     }else{
			if(empty($id_day_actifity_report)){
			  $kirim = array(
					  "service"               =>  $service,
					  "belanja"               =>  $belanja,
					  "service_belanja"       =>  $service_belanja,
					  "p_service"             =>  $p_service,
					  "p_belanja"             =>  $p_belanja,
					  "p_service_plus"        => $p_service_plus,
					  "p_belanja_plus"        =>  $p_belanja_plus,
					  "total_hpp"             => $total_hpp,
					  "id_actifity_report"    => $id_actifity_report,
					  "tanggal"               =>  $date_day,
					  "create_by_users"       =>  $this->session->userdata('id'),
					  "create_date"           =>  date("Y-m-d H:i:s"),
					  "update_by_users"       =>  $this->session->userdata('id')
				  );
			  $this->global_models->insert("d_day_actifity_report", $kirim);
			  $pesan = "Insert Outlet ".$db_cuy;
		   }else{
			  $kirim = array(
					 "service"               =>  $service,
					  "belanja"               =>  $belanja,
					  "service_belanja"       =>  $service_belanja,
					  "p_service"             =>  $p_service,
					  "p_belanja"             =>  $p_belanja,
					  "p_service_plus"        => $p_service_plus,
					  "p_belanja_plus"        =>  $p_belanja_plus,
					  "total_hpp"             => $total_hpp,
					  "id_actifity_report"    => $id_actifity_report,
					  "tanggal"               =>  $date_day,
					  "update_by_users"       =>  $this->session->userdata('id')
				  );
			   
				$hasil_in = $this->global_models->update("d_day_actifity_report", array("id_day_actifity_report" => $id_day_actifity_report), $kirim);
			   
			 $pesan = "Update Outlet ".$db_cuy;
		   }
	 }
   
  }else{
   $pesan = $db_cuy;
   $log_pos = $pesan." | Gagal ".$db_cuy;
   $this->nbscache->put_tunggal_sql("log_pos",$log_pos);
  }  
   
    if($this->session->userdata("outlet_pos_number") > $total_pos_outlet){
        $nomor = $total_pos_outlet;
      }else{
        $nomor = $this->session->userdata("outlet_pos_number") + 1;
      }
      
      $set_ses = array(
          "outlet_pos_number"  => $nomor,
          "total_pos_outlet"   => $total_pos_outlet,
      );
      
      $this->session->set_userdata($set_ses);
      $hasil = array(
          "percent" => Ceil($nomor/$total_pos_outlet * 100),
          "n"       => $nomor,
          "rn"      => $total_pos_outlet,
          "note"    => $pesan,
      );
     
      print json_encode($hasil);
      die;
    
  }
  
  function get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
   /* $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch ); */
    curl_close( $ch );

   /* $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content; */
   // return $header; 
    return $content;
    
}
  
	public function delete($id){
    if($this->global_models->delete("m_outlet", array("id_outlet" => $id)))
      redirect("outlet/index/list/sukses");
    else
      redirect("outlet/index/list/filed");
  }
	public function export_xls(){
    $this->musers->export_xls("data-users");
  }
	public function index($action = "list", $pesan = "hal", $hal = 0){
    $list = $this->moutlet->get();
    $this->template->title('Sistem', "Outlet");
    
    $this->template->build('main', 
      array('message' => $pesan,
            'url'     => base_url()."themes/srabon/",
            'data'    => $list,
            'menu_drop'   => $this->menu,
            'menu'        => "settings",
            'title_table'    => "Outlet Data Table",
            'foot'    => ""
          ));
    $this->template
      ->set_layout('default')
      ->build('main');
	}
  function daftar_bc(){
    $list = $this->moutlet->get_bc();
    $this->template->title('Sistem', "Outlet");
    $view = "daftar-bc";
    if($this->mobile_detect->isMobile()){
      $view = "mobile/m-daftar-bc";
    }
    $this->template->build($view, 
      array('message' => "",
            'url'     => base_url()."themes/srabon/",
            'data'    => $list,
            'menu_drop'   => $this->menu,
            'menu'        => "settings",
            'title_table'    => "Daftar BC",
            'foot'    => ""
          ));
    $this->template
      ->set_layout('default')
      ->build($view);
  }
  function export_master_outlet(){
    $this->moutlet->export_master_outlet();
  }
  function master_outlet(){
    $list = $this->moutlet->get_master_outlet();
//    $this->debug($list, true);
    $this->template->title('Sistem', "Outlet");
    $view = "master-outlet";
    $this->template->build($view, 
      array('message' => "",
            'url'     => base_url()."themes/srabon/",
            'data'    => $list,
            'menu_drop'   => $this->menu,
            'menu'        => "settings",
            'title_table'    => "Daftar Kepala & Owner Outlet",
            'foot'    => ""
          ));
    $this->template
      ->set_layout('default')
      ->build($view);
  }
  
  
  function batch_pos_execute($total_pos_outlet, $tanggal){
    $tanggal = str_replace("_", "-", $tanggal);
//    $data_outlet = $this->global_models->get("m_outlet", array("pos" => $pst['pos_data']));
    $data_outlet = $this->global_models->get_query("
      SELECT *
      FROM m_outlet
      WHERE pos != '' AND last_console IS NOT NULL AND id_status_outlet = 0
      ORDER BY id_outlet ASC
      LIMIT ".$this->session->userdata("outlet_pos_number").", 1
      ");
    
    $id_outlet = $data_outlet[0]->id_outlet;
    $this->cek_actifity($id_outlet);
//      $start = "2014-04-01";
    $start = $this->global_models->get_field("m_outlet", "last_console", array("id_outlet" => $id_outlet));
//      $end = "2014-04-30";
    $end = $tanggal;

    $start_time = strtotime($start);
    $end_time = strtotime($end);

    if($end_time <= $start_time){
      $start = $tanggal;
//        $start = "2014-04-01";
      $start_time = strtotime($start);
    }

    $ct = strtotime("2014-02-22");
    $ct2 = strtotime("2014-02-23");
    $aday = $ct2 - $ct;

    $start_time -= ($aday * 7);
//$log_tanggal = $start."---".$end;
    $selisihnya = $end_time - $start_time;
    $jml_selisih = $selisihnya/$aday;
    if($jml_selisih < 40){
    for($r = $start_time ; $r <= $end_time ; $r += $aday){
//        $this->debug(date("Y-m-d", $r));
      
      $tanggal_fix = date("Y-m-d", $r);

//      $log_tanggal .= $tanggal_fix."---";
      
      $tgl = strtotime($tanggal_fix);
      $date_bulan =  date("n", $tgl);
      $date_year =  date("Y", $tgl);
      $date_day =  date("j", $tgl); 

      $data_report =  $this->global_models->get("m_actifity_report", array("id_outlet" => $id_outlet, "month" => $date_bulan, 'year' => $date_year));

      $id_actifity_report = $data_report[0]->id_actifity_report;
      $day_actifity_report =  $this->global_models->get("d_day_actifity_report", array("id_actifity_report" => $id_actifity_report, "tanggal" => $date_day));
      $id_day_actifity_report = $day_actifity_report[0]->id_day_actifity_report;// die;
//   print "http://192.168.2.141/cgi-bin/iframeots.exe/waProcess?db={$pst['pos_data']}&dt={$pst['tanggal']}";die;
      $data = $this->get_web_page("192.168.2.14/cgi-bin/iframeots.exe/waProcess?db={$data_outlet[0]->pos}&dt={$tanggal_fix}");
      $cek_data = strpos($data,"[tmi]");
      if($cek_data!==false){
          $data1 = explode("[tmi]", $data);  
           $data2 = explode(";", $data1[1]);    

          if(empty($data2[0])){
            $service = "";
          }else{
            $service = str_replace("\r\n", "", $data2[0]);
          }
          if(empty($data2[1])){
            $belanja = "";
          }else{
            $belanja = str_replace("\r\n", "", $data2[1]);
          }
          if(empty($data2[2])){
            $service_belanja = "";
          }else{
            $service_belanja = str_replace("\r\n", "", $data2[2]);
          }
          if(empty($data2[3])){
            $p_service = "";
          }else{
            $p_service = str_replace("\r\n", "", $data2[3]);
          }
          if(empty($data2[4])){
            $p_belanja = "";
          }else{
            $p_belanja = str_replace("\r\n", "", $data2[4]);
          }
          if(empty($data2[5])){
            $p_service_plus = "";
          }else{
            $p_service_plus = str_replace("\r\n", "", $data2[5]);
          }
          if(empty($data2[6])){
            $p_belanja_plus = "";
          }else{
            $p_belanja_plus = str_replace("\r\n", "", $data2[6]);
          }
          if(empty($data2[7])){
            $total_hpp = "";
          }else{
            $total_hpp = str_replace("\r\n", "", $data2[7]);
          }

        if(empty($service) AND empty($belanja) AND empty($service_belanja) AND empty($p_service) AND empty($p_belanja) AND empty($p_service_plus) AND empty($p_belanja_plus) AND empty($total_hpp)){
        $pesan = "Data Outlet ".$data_outlet[0]->name." Tanggal ".$tanggal_fix." | Kosong ";
           $log_pos_kosong = $pesan.$data_outlet[0]->pos." ;#".date("Y-m-d H:i:s");
           $this->nbscache->put_tunggal_sql("log_pos_kosong",$log_pos_kosong);
        }else{
           if(empty($id_day_actifity_report)){
             $kirim = array(
                 "service"               =>  $service,
                 "belanja"               =>  $belanja,
                 "service_belanja"       =>  $service_belanja,
                 "p_service"             =>  $p_service,
                 "p_belanja"             =>  $p_belanja,
                 "p_service_plus"        => $p_service_plus,
                 "p_belanja_plus"        =>  $p_belanja_plus,
                 "total_hpp"             => $total_hpp,
                 "id_actifity_report"    => $id_actifity_report,
                 "tanggal"               =>  $date_day,
                 "create_by_users"       =>  $this->session->userdata('id'),
                 "create_date"           =>  date("Y-m-d H:i:s"),
                 "update_by_users"       =>  $this->session->userdata('id')
               );
             $this->global_models->insert("d_day_actifity_report", $kirim);
             $pesan = "insert";
            }else{
             $kirim = array(
                "service"               =>  $service,
                 "belanja"               =>  $belanja,
                 "service_belanja"       =>  $service_belanja,
                 "p_service"             =>  $p_service,
                 "p_belanja"             =>  $p_belanja,
                 "p_service_plus"        => $p_service_plus,
                 "p_belanja_plus"        =>  $p_belanja_plus,
                 "total_hpp"             => $total_hpp,
                 "id_actifity_report"    => $id_actifity_report,
                 "tanggal"               =>  $date_day,
                 "update_by_users"       =>  $this->session->userdata('id')
               );

             $hasil_in = $this->global_models->update("d_day_actifity_report", array("id_day_actifity_report" => $id_day_actifity_report), $kirim);

            $pesan = "update";
            }
            $this->global_models->update("m_outlet", array("id_outlet" => $id_outlet), array("last_console" => $tanggal_fix));
        }

       }else{
         $pesan = "failed";
         $log_pos = $pesan." outlet ".$data_outlet[0]->name." tanggal ".$tanggal_fix." POS ".$data_outlet[0]->pos;
        $this->nbscache->put_tunggal_sql("log_pos",$log_pos);

       }
    }
  }
  else{
    $pesan = "Terlalu panjang";
  }
    
    
    if($this->session->userdata("outlet_pos_number") > $total_pos_outlet){
      $nomor = $total_pos_outlet;
    }else{
      $nomor = $this->session->userdata("outlet_pos_number") + 1;
    }
      
    $set_ses = array(
        "outlet_pos_number"  => $nomor,
        "total_pos_outlet"   => $total_pos_outlet,
    );

    $this->session->set_userdata($set_ses);
    $hasil = array(
        "percent" => Ceil($nomor/$total_pos_outlet * 100),
        "n"       => $nomor,
        "rn"      => $total_pos_outlet,
        "note"    => $pesan."--".$id_outlet,
        "tanggal" => $log_tanggal
    );
    print json_encode($hasil);
    die;
    
  }
  
  private function cek_actifity($id){
  $bulan = (int) date("m");
    if($this->global_models->get_field("m_actifity_report", "id_actifity_report", 
            array("month"  =>  $bulan, "year" => date("Y"), "id_outlet" => $id)) === FALSE){
      $this->global_models->insert("m_actifity_report", 
              array(
                  "id_outlet" =>  $id,
                  "name"      =>  "Laporan ".date("F")." ".date("Y"),
                  "month"     =>  date("m"),
                  "day_in_month"     =>  date("t"),
                  "year"      =>  date("Y"),
                  "create_by_users" =>  1,
                  "create_date" =>  date("Y-m-d H:i:s"),
                  "update_by_users" =>  1
                  ));
    }
    return true;
  }
  
  function dr(){
    $acti = $this->global_models->get("m_actifity_report", array("id_outlet" => 113));
//    $this->debug($acti, true);
    foreach($acti AS $ac){
      $target = $this->global_models->get("d_day_actifity_report", array("id_actifity_report" => $ac->id_actifity_report, "tanggal" => 0));
      $max_service = (int)(($target[0]->service*1.5)/$ac->day_in_month);
      $max_sb = (int)(($target[0]->service_belanja*1.5)/$ac->day_in_month);
      $max_belanja = (int)(($target[0]->belanja*1.5)/$ac->day_in_month);
      $rata_service = array(30000, 35000, 40000);
      $rata_belanja = array(50000, 60000, 70000, 80000, 100000);
      $kirim = array();
      for($r = 1; $r <= $ac->day_in_month ; $r++){
        $serv = rand(($max_service/2),$max_service);
        $blnj = rand(($max_belanja/2),$max_belanja);
        $sb = rand(($max_sb/2),$max_sb);
        
        $p_serv = $serv * $rata_service[rand(0,2)];
        $p_serv_p = $sb * $rata_service[rand(0,2)];
        $p_bel_p = $sb * $rata_belanja[rand(0,4)];
        $p_bel = $blnj * $rata_belanja[rand(0,4)];
        
        $kirim[] = array(
          "id_actifity_report"        => $ac->id_actifity_report,
          "tanggal"                   => $r,
          "service"                   => $serv,
          "service_belanja"           => $sb,
          "belanja"                   => $blnj,
          "p_service"                 => $p_serv,
          "p_service_plus"            => $p_serv_p,
          "p_belanja_plus"            => $p_bel_p,
          "p_belanja"                 => $p_bel,
          "total_hpp"                 => (($p_bel_p + $p_bel)*85/100),
        );
      }
      $this->global_models->insert_batch("d_day_actifity_report", $kirim);
    }
  }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */